import re
import tkinter as tk
from tkinter import filedialog
import pandas as pd
import os
from openpyxl import Workbook

def select_input_folder_path():
    """选择输入文件夹路径"""
    root = tk.Tk()
    root.withdraw()
    return filedialog.askdirectory(title="选择包含txt文件的文件夹")

def select_output_file_path():
    """选择输出文件路径"""
    root = tk.Tk()
    root.withdraw()
    return filedialog.asksaveasfilename(
        title="选择excel文件保存位置",
        defaultextension=".xlsx",
        filetypes=[("xlsx files", "*.xlsx"), ("All files", "*.*")],
    )

def parse_file_data(file_path):
    """解析单个文件中的Pressure和Height数据"""
    data = []
    pattern = re.compile(r'Pressure\s*=\s*(\d+)\s*Height\s*=\s*(\d+\.\d+)')
    
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            match = pattern.search(line)
            if match:
                pressure = int(match.group(1))
                height = float(match.group(2))
                data.append({'Pressure': pressure, 'Height': height})
    return data

def save_to_excel(output_path, all_data, statistics):
    """将数据保存到Excel文件"""
    try:
        # 创建新的Excel文件
        with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
            # 保存统计数据到第一个sheet
            stats_df = pd.DataFrame(statistics)
            stats_df.to_excel(writer, sheet_name='统计汇总', index=False)
            
            # 保存各文件数据到不同sheet
            for file_name, data in all_data.items():
                # 简化sheet名称（去掉扩展名和特殊字符）
                sheet_name = os.path.splitext(file_name)[0][:30]  # 限制sheet名称长度
                df = pd.DataFrame(data)
                df.to_excel(writer, sheet_name=sheet_name, index=False)
                
        print(f"文件已保存到：{output_path}")
    except Exception as e:
        print(f"保存文件时出错：{e}")

def main():
    input_folder = select_input_folder_path()
    if not input_folder:
        print("未选择输入文件夹，程序退出。")
        return

    output_file = select_output_file_path()
    if not output_file:
        print("未选择输出文件，程序退出。")
        return

    # 收集所有文件数据
    all_data = {}
    statistics = {
        '文件名': [],
        'Pressure平均值': [],
        'Height平均值': [],
        '数据总量': []
    }

    for file_name in os.listdir(input_folder):
        if file_name.endswith('.txt'):
            file_path = os.path.join(input_folder, file_name)
            data = parse_file_data(file_path)
            
            if data:
                # 添加到详细数据
                all_data[file_name] = data
                
                # 计算统计信息
                df = pd.DataFrame(data)
                statistics['文件名'].append(os.path.splitext(file_name)[0])
                statistics['Pressure平均值'].append(round(df['Pressure'].mean(), 2))
                statistics['Height平均值'].append(round(df['Height'].mean(), 2))
                statistics['数据总量'].append(len(df))

    if not all_data:
        print("没有找到有效数据，程序退出。")
        return

    save_to_excel(output_file, all_data, statistics)

if __name__ == "__main__":
    main()